import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import { Card, Col, Button, Tree, message } from 'antd';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import { Link } from 'dva/router';
import TableModal from '../../components/_public/TableModal';

import MyTree from '../../components/_public/MyTree';

import LessonPreview from '../../components/_public/LessonPreview';

import styles from './CoursewareConfig.less';

import { getParamUrl } from '../../utils/formatDataSource';

@connect(({ lesson3, loading }) => ({
  lesson:lesson3,
  loading: loading.models.lesson3,
}))
class CoursewareConfig extends PureComponent {
  state = {
    visible: false,
    treeContentList: [],
    checkedKeys: [],
    selectedQuestions: [],
    currentKey: '',
    currentQuestionType: 1,
    pageMark: [],
    hrLineList: [],
    previewShow: false,
    selectedTrees: [],
  };

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'lesson3/kjConfig',
    });

    dispatch({
      type: 'lesson3/questionList',
    });
  }

  showModal = (item, type) => {
    const { selectedQuestions } = this.state;

    let isAdd = true;
    selectedQuestions.map(one => {
      if (one.key == item.uniqueKey && one.type == type) {
        isAdd = false;
      }
    });
    if (isAdd) {
      // 添加一个新的题型对应的模型
      selectedQuestions.push({
        key: item.uniqueKey,
        type: type, // 1 例题 需要显示：分析/选项/答案等   2 习题
        questions: [],
        questionTypeId: item.id,
      });
    }

    this.setState({
      visible: true,
      selectedQuestions: selectedQuestions,
      currentKey: item.uniqueKey,
      currentQuestionType: type,
    });
  };

  handleOk = e => {
    const { currentKey, currentQuestionType, selectedQuestions = [] } = this.state;
    selectedQuestions.map(_ => {
      if (currentKey == _.key && currentQuestionType == _.type) {
        _.questions = e;
      }
    });

    this.setState({
      visible: false,
      selectedQuestions: [...selectedQuestions],
    });
  };

  handleCancel = e => {
    console.log(e);
    this.setState({
      visible: false,
    });
  };

  getTitleById = (typeId, title) => {
    switch (typeId) {
      case 1:
        return <span>章：{title}</span>;
      case 2:
        return <span>节：{title}</span>;
      case 3:
        return <span>知识点：{title}</span>;
      case 4:
        return <span>方法：{title}</span>;
      case 5:
        return <span>题型：{title}</span>;
    }
  };

  getStyleTitle = typeId => {
    switch (typeId) {
      case 1:
        return styles.zhangTitle;
      default:
        return styles.jieTitle;
    }
  };

  getStyleContent = typeId => {
    switch (typeId) {
      case 1:
        return styles.zhangContent;
      default:
        return styles.jieContent;
    }
  };

  renderTreeNodes = data => {
    const TreeNode = Tree.TreeNode;
    return data.map(item => {
      if (item.sons) {
        return (
          <TreeNode title={item.title} key={item.uniqueKey}>
            {this.renderTreeNodes(item.sons)}
          </TreeNode>
        );
      }
      return <TreeNode title={item.title} key={item.uniqueKey} />;
    });
  };

  resetTreeStatus = data => {
    if (data == null) {
      return;
    }
    data.map(_ => {
      if (_.sons) {
        this.resetTreeStatus(_.sons);
      }
      _.showStatus = 0;
    });
  };

  handlePageMark = (item, type) => {
    this.setState({
      hrLineList: [
        ...this.state.hrLineList,
        {
          key: item.uniqueKey,
          status: type === 1 ? false : true,
        },
      ],
    });
  };

  handleDelQuestion = (key, questionId, type) => {
    const { selectedQuestions = [] } = this.state;
    let arrP = [];
    selectedQuestions.map(_ => {
      if (_.key === key && _.type === type) {
        _.questions = _.questions.filter(s => s.id !== questionId);
      }
      arrP.push(_);
    });

    this.setState({
      selectedQuestions: arrP,
    });
  };

  handleDel = value => {
    const { treeList = [] } = this.props.lesson;
    const { checkedKeys, selectedQuestions, selectedTrees } = this.state;

    this.updateDelStatus(treeList, value);

    const newKey = checkedKeys.filter(c => c != value.uniqueKey);

    const newArr = selectedQuestions.filter(s => s.key != value.uniqueKey);

    const newTree = selectedTrees.filter(s => s.key != value.uniqueKey);

    this.setState({
      treeContentList: treeList,
      checkedKeys: newKey,
      selectedQuestions: newArr,
      selectedTrees: newTree,
    });
  };

  updateDelStatus = (treeList, value) => {
    treeList.map(_ => {
      if (_.uniqueKey == value.uniqueKey) {
        _.showStatus = 0;
        this.resetTreeStatus(_.sons);
      } else {
        if (_.sons) {
          this.updateDelStatus(_.sons, value);
        }
      }
    });
  };

  setQuestionDiv = (item, type) => {
    const { selectedQuestions = [] } = this.state;

    return selectedQuestions.map(_ => {
      if (_.key == item.uniqueKey && _.type == type) {
        return _.questions.map(s => {
          return (
            <div className={styles.question} key={s.id}>
              <span className={styles.stemContent}>{s.stem}</span>
              <span className={styles.stemOperate}>
                <a
                  href="javascript:;"
                  onClick={() => this.handleDelQuestion(item.uniqueKey, s.id, type)}
                >
                  删除
                </a>
              </span>
            </div>
          );
        });
      }
    });
  };

  getHrStatus = item => {
    const { hrLineList } = this.state;
    let res = true;
    hrLineList.map(a => {
      if (a.key === item.uniqueKey) {
        res = a.status;
      }
    });
    return res;
  };

  commonDiv = item => {
    return (
      <div key={item.uniqueKey}>
        <div className={this.getStyleTitle(item.type)}>
          <span className={styles.treeContent}>{this.getTitleById(item.type, item.title)}</span>
          <span className={styles.treeOperate}>
            <a
              href="javascript:;"
              onClick={() => this.handlePageMark(item, 1)}
              hidden={!this.getHrStatus(item)}
            >
              设置分页线
            </a>
            <a
              href="javascript:;"
              onClick={() => this.handlePageMark(item, 2)}
              hidden={this.getHrStatus(item)}
            >
              取消分页线
            </a>
          </span>
        </div>
        <div className={this.getStyleContent(item.type)}>
          <span className={styles.treeContent}>{item.content}</span>
          <div hidden={item.type !== 5}>
            <div>
              <span className={styles.qsLogo_0}>例题</span>
              <span className={styles.qsLogo_1}>
                <a href="javascript:;" onClick={() => this.showModal(item, 1)}>
                  添加
                </a>
              </span>
            </div>
            <div className={styles.questionStem}>{this.setQuestionDiv(item, 1)}</div>
            <div>
              <span className={styles.qsLogo_0}>习题</span>
              <span className={styles.qsLogo_1}>
                <a href="javascript:;" onClick={() => this.showModal(item, 2)}>
                  添加
                </a>
              </span>
            </div>
            <div className={styles.questionStem}>{this.setQuestionDiv(item, 2)}</div>
          </div>
          <div hidden={this.getHrStatus(item)}>
            <hr className={styles.hrLine} />
          </div>
        </div>
      </div>
    );
  };
  getByKey = data => {
    return data.map(item => {
      if (item.showStatus == 1) {
        if (item.sons) {
          return (
            <div key={item.uniqueKey}>
              {this.commonDiv(item)}
              {this.getByKey(item.sons)}
            </div>
          );
        }
        return this.commonDiv(item);
      }
    });
  };

  checkKeyContains = (data, keys) => {
    data.map(d => {
      if (d.sons) {
        this.checkKeyContains(d.sons, keys);
      }
      keys.map(k => {
        if (k == d.uniqueKey) {
          d.showStatus = 1;
        }
      });
    });
  };

  _m_m_1 = (data, arr) => {
    data.map(d => {
      if (d.showStatus === 1) {
        if (d.sons) {
          arr.push({
            title: d.title,
            content: d.content,
            type: d.type,
            key: d.uniqueKey,
            pageMark: 0,
            id: d.id,
            q_1: [],
            q_2: [],
          });
          this._m_m_1(d.sons, arr);
        } else {
          arr.push({
            title: d.title,
            content: d.content,
            type: d.type,
            key: d.uniqueKey,
            pageMark: 0,
            id: d.id,
            q_1: [],
            q_2: [],
          });
        }
      }
    });
  };

  _m_m_2 = data => {
    const { selectedQuestions } = this.state;
    data.map(d => {
      selectedQuestions.map(s => {
        if (s.key === d.key) {
          if (s.type === 1) {
            d.q_1 = s.questions;
          }
          if (s.type === 2) {
            d.q_2 = s.questions;
          }
        }
      });
    });
  };

  _m1 = (checkedKeys, totalKeys) => {
    const { treeList = [] } = this.props.lesson;

    let arr = [];

    this.resetTreeStatus(treeList);

    this.checkKeyContains(treeList, totalKeys);

    // 封装选中的数据
    this._m_m_1(treeList, arr);

    this.setState({
      treeContentList: treeList,
      checkedKeys: checkedKeys,
      selectedTrees: arr,
    });
  };

  _m2 = () => {
    this.setState({
      previewShow: false,
    });
  };

  _m3 = () => {
    const { selectedTrees = [] } = this.state;

    // 封装选中的题目
    this._m_m_2(selectedTrees);

    let arr = selectedTrees;

    this.setState({
      selectedTrees: arr,
      previewShow: true,
    });
  };
  _m4 = () => {
    const { treeContentList } = this.state;
    this.resetTreeStatus(treeContentList);
    this.setState({
      treeContentList: [...treeContentList],
      checkedKeys: [],
      selectedTrees: [],
    });
  };

  _m5 = () => {
    const { selectedTrees, hrLineList, selectedQuestions } = this.state;
    const { dispatch, location: { search } } = this.props;

    selectedTrees.map(s => {
      hrLineList.map(h => {
        if (h.key === s.key) {
          s.pageMark = !h.status ? 0 : 1;
        }
      });
    });

    const params = getParamUrl(search);

    dispatch({
      type: 'lesson3/coursewareAdd',
      payload: {
        selectedTrees,
        selectedQuestions,
        ...params,
      },
    });

    // console.log(selectedTrees)
  };

  _m6 = value => {
    this.setState({
      visible: value,
    });
  };

  _m7 = (page, pageSize) => {
    const { dispatch } = this.props;

    dispatch({
      type: 'lesson3/questionList',
      payload: {
        page,
        pageSize,
      },
    });
  };

  render() {
    const { treeList = [], questionListInfo } = this.props.lesson;

    const { treeContentList } = this.state;

    let selectedQuestion = [];

    return (
      <PageHeaderLayout>
        <Col span={4}>
          <Card bordered={true} style={{ height: '900px' }}>
            <MyTree
              dataSource={treeList}
              checkedKeys={this.state.checkedKeys}
              handleCheck={this._m1}
            />
          </Card>
        </Col>
        <Col span={20}>
          <Card bordered={true}>{this.getByKey(treeContentList)}</Card>
          <Card>
            <div>
              <Button type="primary" className={styles.button} onClick={this._m5}>
                保存
              </Button>
              <Button className={styles.button} onClick={this._m4}>
                取消
              </Button>
              <Button type="primary" className={styles.button} onClick={this._m3}>
                预览
              </Button>
            </div>
          </Card>
        </Col>
        <div>
          <TableModal
            visible={this.state.visible}
            onClickModal={this._m6}
            onClickSubmit={this.handleOk}
            dataSource={questionListInfo}
            getPageData={this._m7}
          />
        </div>
        <LessonPreview
          visible={this.state.previewShow}
          onOk={this._m2}
          onCancel={this._m2}
          dataSource={this.state.selectedTrees}
        />
      </PageHeaderLayout>
    );
  }
}

export default CoursewareConfig;
